import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:image_picker/image_picker.dart';

class PersonalCenterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<PersonalCenterPage> {
  Map userInfo = {};
  bool loadSuccess = false;
  final picker = ImagePicker();

  List list = [
    {
      "icon": "assets/my_icon1.png",
      "title": "头像",
      "avatar": true,
      "route": "",
      "height": 150.w,
      "showArrow": true,
      "rightText": ""
    },
    {
      "icon": "assets/my_icon2.png",
      "title": "姓名",
      "route": "",
      "avatar": false,
      "height": 110.w,
      "showArrow": false,
      "rightText": ""
    },
    {
      "icon": "assets/my_icon3.png",
      "title": "部门",
      "avatar": false,
      "route": "",
      "height": 110.w,
      "showArrow": false,
      "rightText": ""
    },
  ];

  @override
  void initState() {
    super.initState();
    getUserInfo();
  }

  // 获取用户信息
  getUserInfo() {
    Utils.getUserId().then((userId) => {
          DioUtils.request("common/getDetails",
              context: context,
              method: "POST",
              params: {'id': userId}, onSuccess: (res) {
            if (res['code'] == 1) {
              setState(() {
                loadSuccess = true;
                userInfo = res['data'];
                list[1]['rightText'] = userInfo['name'];
                list[2]['rightText'] = userInfo['department_name'];
              });
            } else {
              Utils.showText(text: res['msg']);
            }
          }, onError: (error) {
            // Toast.show(error);
          })
        });
  }

  Future getImage() async {
    Navigator.of(context).pop();
    final pickedFile = await picker.getImage(source: ImageSource.gallery);
    _upLoadImage(pickedFile);
  }

  Future getPhoto() async {
    Navigator.of(context).pop();
    final pickedFile = await picker.getImage(source: ImageSource.camera);
    _upLoadImage(pickedFile);
  }

  //上传图片
  _upLoadImage(PickedFile image) async {
    if (image != null) {
      String path = image.path;
      var name = path.substring(path.lastIndexOf("/") + 1, path.length);

      FormData formdata = FormData.fromMap(
          {"file": await MultipartFile.fromFile(path, filename: name)});

      DioUtils.request("Upload/uploadAvatar",
          context: context, method: "POST", params: formdata, onSuccess: (res) {
        if (res['code'] == 1) {
          getUserInfo();
        } else {
          Utils.showText(text: res['msg']);
        }
      }, onError: (error) {});
    }
  }

  Widget _buildAvatar() {
    if (loadSuccess) {
      if (userInfo['avatar'].toString().isNotEmpty) {
        return Image.network(DioUtils.API_PREFIX + userInfo['avatar'],
            width: 120.w, height: 120.w, fit: BoxFit.cover);
      } else {
        return Image.asset('assets/avatar.png', width: 120.w, height: 120.w);
      }
    } else {
      return Container(
        width: 120.w,
        height: 120.w,
        color: Utils.hexToColor('#F1F3F4'),
      );
    }
  }

  Widget _buildNav(context) {
    int index = 0;
    List<Widget> widget = [];

    for (var item in list) {
      index++;
      widget.add(Column(
        children: <Widget>[
          InkWell(
            onTap: () {
              if (item['avatar']) {
                showModalBottomSheet(
                  context: context,
                  barrierColor: Color.fromRGBO(0, 0, 0, 0.2),
                  backgroundColor: Colors.transparent,
                  builder: (BuildContext context) {
                    return Container(
                      height: 350.w,
                      child: Column(
                        children: <Widget>[
                          Container(
                            width: 700.w,
                            height: 100.w,
                            child: ElevatedButton(
                              onPressed: getPhoto,
                              child: Text(
                                '拍照',
                                style: TextStyle(
                                    color: Utils.hexToColor('#297CFF'),
                                    fontWeight: FontWeight.w500),
                              ),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.vertical(
                                        top: Radius.circular(12.w))),
                              ),
                            ),
                          ),
                          Container(
                            width: 700.w,
                            height: 1.w,
                            color: Utils.hexToColor('#E6E6E6'),
                          ),
                          Container(
                            width: 700.w,
                            height: 100.w,
                            child: ElevatedButton(
                              onPressed: getImage,
                              child: Text(
                                '我的相册',
                                style: TextStyle(
                                    color: Utils.hexToColor('#297CFF'),
                                    fontWeight: FontWeight.w500),
                              ),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.vertical(
                                        bottom: Radius.circular(12.w))),
                              ),
                            ),
                          ),
                          Container(
                            width: 700.w,
                            height: 100.w,
                            margin: EdgeInsets.only(top: 20.w),
                            child: ElevatedButton(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: Text(
                                '取消',
                                style: TextStyle(
                                    color: Utils.hexToColor('#999999'),
                                    fontWeight: FontWeight.w500),
                              ),
                              style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.white,
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12.w)),
                              ),
                            ),
                          )
                        ],
                      ),
                    );
                  },
                );
              }
            },
            child: Container(
              height: item['height'],
              padding: EdgeInsets.fromLTRB(0.w, 0.w, 30.w, 0.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(left: 27.w),
                      child: Text(item['title'],
                          style: TextStyle(
                              color: Utils.hexToColor('#333333'),
                              fontSize: 16)),
                    )
                  ]),
                  Row(
                    children: <Widget>[
                      Offstage(
                          offstage: item['avatar'] ? false : true,
                          child: Container(
                              width: 120.w,
                              height: 120.w,
                              margin: EdgeInsets.only(right: 26.w),
                              decoration: BoxDecoration(
                                border: new Border.all(
                                    color: Colors.white, width: 4.w),
                                borderRadius: BorderRadius.circular(120.w),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(120.w),
                                // child: Image.asset('assets/avatar.png', width: 120.w, height: 120.w,),
                                child: _buildAvatar(),
                              ))),
                      Offstage(
                        offstage: item['showArrow'] ? false : true,
                        child: Image.asset('assets/arrow_r_n.png', width: 13.w),
                      ),
                      Offstage(
                          offstage: item['showArrow'] ? true : false,
                          child: Text(item['rightText'],
                              style: TextStyle(
                                  color: Utils.hexToColor('#999999'),
                                  fontSize: 16)))
                    ],
                  ),
                ],
              ),
            ),
          ),
          Offstage(
            offstage: index == 3 ? true : false,
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(color: Utils.hexToColor('#F7F7F7')))),
            ),
          )
        ],
      ));
    }
    return Column(children: widget);
  }

  Widget build(BuildContext content) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        appBar: TopBar(
          title: '个人中心',
        ),
        body: Container(
            height: double.infinity,
            color: Utils.hexToColor('#F5F6FA'),
            child: SingleChildScrollView(
                child: Container(
                    margin: EdgeInsets.only(top: 24.w),
                    child: Column(children: <Widget>[
                      Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                          ),
                          child: _buildNav(context))
                    ])))));
  }
}
